package com.sci.web.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailUtil {
	
	
	
	
	
	
	public static String serviceQQ = "949438714";
	public static String autherCode = "wcdilczsesxlbdce";
	public static String serviceEmail = serviceQQ+"@qq.com";
	public static String emailTitle = "lexy博客站—邮箱验证";
	public static String emailContent = "<span>亲爱的用户：</span><br/><p>您好！</p><br/><p>感谢您使用<a href=\"_HREF_\">lexy博客站</a>。您正在进行邮箱验证，请在验证码输入框中输入此次验证码。</p><p><span style=\"color:red;font-weight: 800\">_CODE_</span>以完成验证。</p><br/><p>如非本人操作，请忽略此邮件，由此给您带来的不便请谅解！</p><p><a href=\"_HREF_\">lexy博客站</a><a href=\"_HREF_\">_HREF_ADDR_</a></p> ";	
	
	
	
	public static boolean sendEmialCode(String recipientEmail , String emailTitle,  String emailContent){
		
		boolean flag = false;
		Properties prop = new Properties();
		// 开启debug调试，以便在控制台查看
		prop.setProperty("mail.debug", "true"); 
		// 设置邮件服务器主机名
		prop.setProperty("mail.host", "smtp.qq.com");
		// 发送服务器需要身份验证
		prop.setProperty("mail.smtp.auth", "true");
		// 发送邮件协议名称
		prop.setProperty("mail.transport.protocol", "smtp");

		// 开启SSL加密，否则会失败
		MailSSLSocketFactory sf =null ;
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			prop.put("mail.smtp.ssl.enable", "true");
			prop.put("mail.smtp.ssl.socketFactory", sf);
			
			// 创建session
			Session session = Session.getInstance(prop);
			// 通过session得到transport对象
			Transport ts = session.getTransport();
			// 连接邮件服务器：邮箱类型，帐号，授权码代替密码（更安全）
			ts.connect("smtp.qq.com",serviceQQ, autherCode);//后面的字符是授权码，用qq密码反正我是失败了（用自己的，别用我的，这个号是我瞎编的，为了。。。。）
			// 创建邮件
			Message message = createSimpleMail(session , recipientEmail , emailTitle , emailContent);
			// 发送邮件
			ts.sendMessage(message, message.getAllRecipients());
			ts.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

		/**
		* @Method: createSimpleMail
		* @Description: 创建一封只包含文本的邮件
		*/
		public static MimeMessage createSimpleMail(Session session , String recipientEmail , String emailTitle, String emailContent) throws Exception {
			
			// 创建邮件对象
			MimeMessage message = new MimeMessage(session);
			// 指明邮件的发件人
			message.setFrom(new InternetAddress(serviceEmail));
			// 指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
			// 邮件的标题
			message.setSubject(emailTitle);
			// 邮件的文本内容
			message.setContent(emailContent, "text/html;charset=UTF-8");
			// 返回创建好的邮件对象
			return message;
		}

	   
		public static void main(String[] args) {
			sendEmialCode("949710290@qq.com", emailTitle,emailContent);
		}
		
		
		
	
}